import { defineStore } from 'pinia'
import { ref } from 'vue'
import request from '@/utils/request'
import router from '@/router'
import { message } from 'ant-design-vue'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('user') || 'null'))

  // 登录
  const login = async (username, password) => {
    try {
      const res = await request.post('/auth/login', { username, password })
      token.value = res.data.token
      userInfo.value = res.data.user
      
      localStorage.setItem('token', res.data.token)
      localStorage.setItem('user', JSON.stringify(res.data.user))
      
      message.success('登录成功')
      router.push('/')
    } catch (error) {
      console.error('登录失败：', error)
    }
  }

  // 退出登录
  const logout = async () => {
    try {
      await request.post('/auth/logout')
    } catch (error) {
      console.error('退出登录失败：', error)
    } finally {
      token.value = ''
      userInfo.value = null
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      router.push('/login')
      message.success('退出成功')
    }
  }

  // 获取用户信息
  const getUserInfo = async () => {
    try {
      const res = await request.get('/auth/info')
      userInfo.value = res.data
      localStorage.setItem('user', JSON.stringify(res.data))
    } catch (error) {
      console.error('获取用户信息失败：', error)
    }
  }

  return {
    token,
    userInfo,
    login,
    logout,
    getUserInfo
  }
})

